package com.yurenmatou.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yurenmatou.bean.APIBean;
import com.yurenmatou.bean.APIData;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

public class HttpUtils {


    public static <T> void doRequestApi(String requestMethod, TreeMap<String, Object> params, CallBackApi<T> callBackApi) {
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        try {
            LogUtils.printMessage("第一步\r\n");
            HttpURLConnection urlConnection = (HttpURLConnection) new URL(addPPP(params)).openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setRequestMethod(requestMethod);
            StringBuffer sb = new StringBuffer();
            inputStream = urlConnection.getInputStream();
            LogUtils.printMessage("第二步\r\n");
            if (null != inputStream && inputStream.available() > 0) {
                int len = 0;
                inputStreamReader = new InputStreamReader(inputStream);
                bufferedReader = new BufferedReader(inputStreamReader);
                String content = null;
                while ((content = bufferedReader.readLine()) != null) {
                    sb.append(content);
                }
            }
            LogUtils.printMessage("第三步\r\n");
            callBackApi.callbackData(new Gson().fromJson(sb.toString(), new TypeToken<APIBean<APIData>>() {
            }.getType()), null);
            LogUtils.printMessage("第四步\r\n");
        } catch (Exception e) {
            e.printStackTrace();
            callBackApi.callbackData(null, e);
        } finally {
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                }
            }
            if (null != inputStreamReader) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static String jdk(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] md5 = md.digest(data.getBytes(StandardCharsets.UTF_8));
            // 将处理后的字节转成 16 进制，得到最终 32 个字符
            StringBuilder sb = new StringBuilder();
            for (byte b : md5) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String addPPP(TreeMap<String, Object> params) {
        StringBuffer sb = new StringBuffer();
        sb.append(IMenu.a(false));
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            sb.append(entry.getValue());
        }
        params.put(AU.d(SystemUtils.a, J.v().substring(0, 16)), IMenu.a(false));
        params.put(AU.d(StringUtil.a, J.v().substring(0, 16)), jdk(sb.toString()));
        sb = new StringBuffer();
        sb.append(IMenu.a(true));
        int index = 0;
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            index++;
            Object value = entry.getValue();
            if (entry.getKey().equals("where")) {
                value = URLEncoder.encode(value.toString());
            }
            if (entry.getKey().equals("data")) {
                value = URLEncoder.encode(value.toString());
            }
            if (index == params.size()) {
                sb.append(entry.getKey() + "=" + value);
            } else {
                sb.append(entry.getKey() + "=" + value).append("&");
            }
        }
        return sb.toString();
    }

}
